import draggable from "vuedraggable";
import FormRender from "../../components/form/form-render.vue";
import FormDesignRender from "../../components/form/form-design-render.vue";
import FormComponentConfig from "../../components/form/form-config/form-component-config.vue";
import { baseComponents } from "../../components/form/form-config/component-type-export.js";

export default {
  title:"FormDesign案例",
  name: "FormDesign",
  components: {
    draggable,
    FormComponentConfig,
    FormDesignRender,
    FormRender,
  },
  data() {
    return {
      // 左侧 开始拖拽标识(拖拽时,隐藏页面部分属性)
      isStart: false,
      // 左侧组件集合
      baseComponents,
      // 中间表单draggable组件配置
      draggableFormOptions:{
        animation: 300,
        chosenClass: 'choose',
        sort: true,
      }
    };
  },
  created() {
    console.log('表单是否存在',!this.$store.state.design.formItems)
    // 重新进入时，清除选中
    this.$store.state.selectFormItem = '';
    if(!this.$store.state.design.formItems){
      this.loadInitFrom();
    }
  },
  computed: {
    // 表单信息
    forms() {
      console.log('this.$store.state.design',this.$store.state.design)
      return this.$store.state.design.formItems || [];
    //   return [{
    //     "title": "统计模块",
    //     "name": "StatisticalModule",
    //     "icon": "",
    //     "props": {
    //         "required": false,
    //         "enablePrint": true
    //     },
    //     "id": "field5465543710685"
    // }]
    },
    // 选中的表单元素
    selectFormItem: {
      get() {
        console.log('选中的表单元素',this.$store.state.selectFormItem)
        return this.$store.state.selectFormItem;
      },
      set(val) {
        this.$store.state.selectFormItem = val;
      },
    },
    nodeMap() {
      return this.$store.state.nodeMap;
    },
  },
  methods: {
    /**
     * 配置Id
     */
    getId() {
      return (
        "field" + (Math.floor(Math.random() * (99999 - 10000)) + 10000).toString() + new Date().getTime().toString().substring(5)
      );
    },

    /**
     * 初始化表单
     */
    loadInitFrom() {
      this.$store.commit("loadForm", {
        formId: null,
        formName: "未命名页面",
        logo: {
          icon: "el-icon-eleme",
          background: "#1e90ff",
        },
        settings: {
          commiter: [],
          admin: [],
          sign: false,
          notify: {
            types: ["APP"],
            title: "消息通知标题",
          },
        },
        groupId: undefined,
        formItems: [],
        process: {
          id: "root",
          parentId: null,
          type: "ROOT",
          name: "发起人",
          desc: "任何人",
          props: {
            assignedUser: [],
            formPerms: [],
          },
          children: {},
        },
        remark: "备注说明",
      });
    },

    /**
     * 复制节点
     * @param { Object } node 节点信息
     * @param { Number } index 索引下标
     */
    copyComponentEvent(node, index) {
      // TODO 对于嵌套节点暂时还有问题 and 复制出来的id一致,导致删除/选中时，为同一个节点
      console.log(node, index)
      let nodeInfo = JSON.parse(JSON.stringify(node));
      nodeInfo.id = this.getId();
      this.forms.splice(index + 1, 0, Object.assign({}, nodeInfo));
    },

    /**
     * 提交模板
     */
    saveTemplateEvent(){
      let template = JSON.parse(JSON.stringify(this.forms));
      this.$store.commit("setFormItems",template)
      console.log('保存模板',template)
    },

    /**
     * 根据索引下标删除节点
     * @param { Number } index 索引下标
     */
    deleteComponentEvent(index) {
      this.$confirm(
        "删除组件将会连带删除包含该组件的条件以及相关设置，是否继续?",
        "提示", {
          confirmButtonText: "确 定",
          cancelButtonText: "取 消",
          type: "warning",
        }
      ).then(() => {
        if (this.forms[index].name === "SpanLayout") {
          //删除的是分栏则遍历删除分栏内所有子组件
          this.forms[index].props.items.forEach((item) => {
            this.removeFormItemAbout(item);
          });
          this.forms[index].props.items.length = 0;
        } else {
          this.removeFormItemAbout(this.forms[index]);
        }
        this.forms.splice(index, 1);
      });
    },

    /**
     * 删除具体节点
     * @param { Object } item 对应项
     */
    async removeFormItemAbout(item) {
      this.nodeMap.forEach((node) => {
        //搜寻条件，进行移除
        if (node.type === "CONDITION") {
          node.props.groups.forEach((group) => {
            let i = group.cids.remove(item.id);
            if (i > -1) {
              //从子条件移除
              group.conditions.splice(i, 1);
            }
          });
        }
        //搜寻权限，进行移除
        if ( node.type === "ROOT" || node.type === "APPROVAL" || node.type === "CC" ) {
          node.props.formPerms.removeByKey("id", item.id);
          if (node.props.formUser === item.id) {
            node.props.formUser = "";
          }
        }
      });
    },
    
    /**
     * 拖拽克隆
     * @param {*} obj 
     */
    cloneNode(obj) {
      obj.id = this.getId();
      return JSON.parse(JSON.stringify(obj));
    },

    /**
     * 选中组件事件
     * @param { Object } item 选中的组件信息
     */
    selectItemEvent(item) {
      this.selectFormItem = item;
    },

    /**
     * 设置被选中样式
     * @param { Obeject } item 选中的组件信息
     */
    setSelectedStyleEvent(item) {
      return this.selectFormItem && this.selectFormItem.id === item.id ? "border-left: 4px solid #409eff" : "";
    },

    /**
     * 校验事件
     */
    validate() {
      let err = [];
      if (this.forms.length > 0) {
        let titleSet = new Set();
        this.forms.forEach((item) => {
          //主要校验表格及分栏/选择器/表单名称/是否设置
          this.validateItem(err, titleSet, item);
        });
      } else {
        err.push("表单为空，请添加组件");
      }
      return err;
    },

    /**
     * 校验不通过处理
     * @param {*} err 
     * @param {*} titleSet 
     * @param {*} item 
     */
    validateItem(err, titleSet, item) {
      if (titleSet.has(item.title) && item.name !== "SpanLayout") {
        err.push(`表单 ${item.title} 名称重复`);
      }
      titleSet.add(item.title);
      if (item.name === "SelectInput" || item.name === "MultipleSelect") {
        if (item.props.options.length === 0) {
          err.push(`${item.title} 未设置选项`);
        }
      } else if (item.name === "TableList") {
        if (item.props.columns.length === 0) {
          err.push(`明细表 ${item.title} 内未添加组件`);
        }
      } else if (item.name === "SpanLayout") {
        if (item.props.items.length === 0) {
          err.push("分栏内未添加组件");
        } else {
          item.props.items.forEach((sub) =>
            this.validateItem(err, titleSet, sub)
          );
        }
      }
    },
  },
};
